import Sheet from "@/components/Sheet";
import { Card, Space, Button, DatePicker, Select, Modal, Tabs, message, Upload, Input, Flex, Typography } from "antd";
import { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { setShowBtnTool } from "@/store/modules/style";
import BtnTool from "@/components/BtnTool";
import { sikuhshblurfindAPI, sikuhshdeleteallAPI } from "@/apis";
import { UploadOutlined } from '@ant-design/icons';
import UploadHshModal from "./UploadHshModal/index"

const columns = [
  {
    title: '序号',
    dataIndex: 'ID',
  },
  {
    title: '编号',
    dataIndex: 'CODE',
  },
  {
    title: '分析报告批次',
    dataIndex: 'FXBGPC' 
  },
  {
    title: '提供时间',
    dataIndex: 'TGSJ'
  },
  {
    title: '所属二级',
    dataIndex: 'SSEJ'
  },
  {
    title: '成员单位',
    dataIndex: 'CYDW'
  },
  {
    title: '交易对手',
    dataIndex: 'JYDS'
  },
  {
    title: '涉险类型',
    dataIndex: 'SXLX'
  },
  {
    title: '交易类型',
    dataIndex: 'JYLX'
  },
  {
    title: '交易笔数',
    dataIndex: 'JYBS'
  },
  {
    title: '交易金额（万元）',
    dataIndex: 'JYJE'
  },
  {
    title: '反馈情况',
    dataIndex: 'FKQK'
  },
  {
    title: '命中情况',
    dataIndex: 'MZQK'
  }
]

export default function Maoyifengxian() {
  // 分页参数
  const [page, setPage] = useState({ pageNum: 1, pageSize: 10 });
  // 选中行
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  // 数据源
  const [dataSource, setDataSource] = useState({ data: [], total: 0 });
  // 搜索参数状态
  const [searchParams, setSearchParams] = useState({});
  // 加载状态
  const [loading, setLoading] = useState(false); 
  const dispatch = useDispatch();
  // 控制弹出框状态，默认关闭
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 搜索框参数
  const [company, setCompany] = useState(null)
  // 交易类型参数
  const [jylx, setJylx] = useState(null)
  // 打开弹出框
  const showModal = () => {
    setIsModalOpen(true);
  };
  // 弹出框确认按钮事件
  const handleOk = () => {
    setIsModalOpen(false);
  };
  // 弹出框取消按钮事件
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  // 获取数据方法
  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await sikuhshblurfindAPI({
        pagenum: page.pageNum,
        pagesize: page.pageSize,
        ...searchParams
      });
      
      // 根据实际API响应结构调整
      setDataSource({
        data: res.data.data || [],
        total: res.data.total || 0
      });
    } catch (error) {
      console.error('数据获取失败:', error);
    } finally {
      setLoading(false);
    }
  };
  // 当page或searchParams变化时重新获取数据
  useEffect(() => {
    fetchData();
  }, [page, searchParams]);
  const handleSearch = () => {
    let params = {
      'company': company || null,
      'jylx': jylx || null
    }
    // 点击搜索时更新搜索参数，并重置页码
    setSearchParams(params);
    setPage(prev => ({ ...prev, pageNum: 1 }));
  };
  const handleClear = () => {
    setCompany(null)
    setJylx(null)
  };
  const handlePage = (pageNum, pageSize) => {
    setPage({ pageNum, pageSize });
  };
  const handleSelChange = (keys, rows) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows)
    dispatch(setShowBtnTool(keys.length > 0));
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: handleSelChange,
  };
  const handleQueryChange = e => {
    setCompany(e.target.value)
  }
  const handleSelectChange = value => {
    setJylx(value)
  };
  // 删除
  const handleDel = () => {
    // console.log('删除的 keys:', selectedRowKeys);
    // console.log('删除的数据:', selectedRows);
    let ids = {
      "ids": selectedRowKeys
    }
    sikuhshdeleteallAPI({
      params: ids
    }).then((res) => {
      if (res.code == 200){
          message.success(res.message);
          // 刷新数据
          fetchData();
      }else{
          message.error(res.message);
      }
    }).catch(() => {
      message.error("删除失败！")
    })
  };
  return (
    <div>
      <h2 className="headline">司库核实函信息</h2>
      <Space direction="vertical" size={16} style={{ width: "100%" }}>
        <Card>
            <Flex justify={'space-between'} align={'center'} horizontal>
                <div>
                    <Space>
                        <Input placeholder="请输入成员单位&交易对手" style={{ width: 220 }} onChange={handleQueryChange} value={company}/>
                        <Select
                          placeholder={"交易类型"}
                          style={{ width: 100 }}
                          onChange={handleSelectChange}
                          value={jylx}
                          options={[
                            { value: '付款', label: '付款' },
                            { value: '收款', label: '收款' },
                          ]}
                        />
                        <Button type="primary" onClick={handleSearch}>搜索</Button>
                        <Button type="default" onClick={handleClear}>重置</Button>
                    </Space>
                </div>
                <Button type="primary" icon={<UploadOutlined />} onClick={showModal}>上传核实函数据</Button>
            </Flex>
            <Modal
                title="上传核实函数据"
                closable={{ 'aria-label': 'Custom Close Button' }}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                width={1000}
                footer={null}
            >
                <UploadHshModal onrefresh={fetchData}/>
            </Modal>
        </Card>
        <Card>
          <Sheet 
            columns={columns} 
            dataSource={{
              data: dataSource.data,
              total: dataSource.total
            }} 
            rowSelection={rowSelection} 
            rowKey='ID' 
            page={page} 
            onChange={handlePage}
            loading={loading}
          />
        </Card>
      </Space>
      <BtnTool 
        total={`已选择 ${selectedRowKeys.length} 项`} 
        isShow={selectedRowKeys.length > 0} 
        isSave={false} 
        onDel={handleDel}
      />
    </div>
  )
}